<template>
  <div class="Server">
    <el-row>
      <!-- 头部2，创建按钮 及搜索框 -->
      <el-col :span="24">
        <el-card class="Server-head-card" shadow="never" :body-style="{padding:'10px'}">
          <!-- float属性，会将多个同级标签放在同一行 -->
          <div style="float: left;margin-right:10px;">
            <el-button  size="small" type="primary" icon="Edit"  disabled @click="creategitDrawer = true">注册git库</el-button>
            <el-button  size="small" type="primary" icon="Edit"  disabled @click="updatagitDrawer = true">更新git库</el-button>
          </div>
          <div>
            <el-button size="small" type="primary" plain icon="Edit" @click="getServers()">搜索</el-button>
            <el-input class="Server-head-search" size="small" clearable placeholder="请输入" v-model='searchValue'></el-input>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <div>
          <el-card class="Server-body-card" shadow="never" :body-style="{padding:'5px'}">
            <el-table
                style="width:100%;font-size:12px;margin-bottom:10px;"
                :data="gitdatalist"
                v-loading="appLoading">
              <el-table-column width="20"></el-table-column>


              <el-table-column label="群组" width="180">
                <template v-slot="scope">
<!--                  <el-tag>{{ scope.row.name_with_namespace }}</el-tag>-->
                  <el-tag>{{ scope.row.name_with_namespace.split(' / ')[0] }}</el-tag>
                </template>
              </el-table-column>

              <el-table-column label="代码库名称" width="180">
                <template v-slot="scope">
                  <el-tag>{{ scope.row.name }}</el-tag>
                </template>
              </el-table-column>

              <el-table-column label="访问地址测试" width="500">
                <template v-slot="scope">
                  <el-tag>{{ scope.row.http_url_to_repo }}</el-tag>
                </template>
              </el-table-column>


<!--              <el-table-column align=center label="操作" min-width="150">-->
<!--                <template v-slot="scope">-->
<!--                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="SSH(scope.$index, scope.row)" >代码库设置</el-button>-->
<!--                </template>-->
<!--              </el-table-column>-->

            </el-table>
            <el-pagination
                class="Server-body-pagination"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pagesizeList"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :prev-click="getServers"
                :total="ServerTotal">
            </el-pagination>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 创建 -->
    <el-drawer
        v-model="creategitDrawer"
        direction="rtl"
        :before-close="handleClose"
        title="注册git仓库">
      <template #default>
        <!-- flex布局,居中 -->
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
            <!-- rules 定义form表单校验规则 -->
            <el-form ref="createserverData" :rules="createserverRules" :model="createserverData" label-width="80px">
              <!-- prop用于rules中的校验规则的key -->
              <el-form-item class="deploy-create-form" label="git名称" prop="name">
                <el-input v-model="gitname" readonly ></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="git_token" prop="git_token">
                <el-input v-model="createserverData.git_token"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="git_url" prop="git_url">
                <el-input v-model="createserverData.git_url"></el-input>
              </el-form-item>

            </el-form>
          </el-col>
        </el-row>
      </template>
      <!-- 插槽，抽屉footer -->
      <template #footer>
        <!-- 点击后赋值false，隐藏抽屉 -->
        <el-button @click="creategitDrawer=false">取消</el-button>
        <!--        <el-button type="primary" @click="createserverFunc()">立即创建</el-button>-->
        <el-button type="primary" @click="submitForm('createserverData')">立即创建</el-button>

      </template>
    </el-drawer>

    <!-- 修改 -->
    <el-drawer
        v-model="updatagitDrawer"
        direction="rtl"
        :before-close="handleClose"
        title="修改服务器">
      <template #default>
        <!-- flex布局,居中 -->
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
            <!-- rules 定义form表单校验规则 -->
            <el-form ref="updategitData"  :model="updategitData" label-width="80px">
              <!-- prop用于rules中的校验规则的key -->
              <el-form-item class="deploy-create-form" label="git名称" prop="name">
                <el-input v-model="gitname" readonly ></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="git_token" prop="git_token">
                <el-input v-model="createserverData.git_token"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="git_url" prop="git_url">
                <el-input v-model="createserverData.git_url"></el-input>
              </el-form-item>


            </el-form>
          </el-col>
        </el-row>
      </template>
      <!-- 插槽，抽屉footer -->
      <template #footer>
        <!-- 点击后赋值false，隐藏抽屉 -->
        <el-button @click="updatagitDrawer=false">取消</el-button>
        <el-button type="primary" @click="updatagitFunc()">确定</el-button>
      </template>
    </el-drawer>
  </div>

  <SSH v-model:visible="sshDialogVisible" :row="currentRow" ></SSH>
</template>

<script>
import common from "../common/Config";
import httpClient from '@/request';
import SSH from "@/views/cmdb/servers/SSH";

export default {
  data() {
    return {

      //编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      searchValue: '',
      appLoading: false,
      authentication:'',
      //服务器组列表
      ServergroupList: [],
      getServersgroupData: {
        url: common.servergroupList,
        HostServers:'',
      },

      //凭据列表
      CredentialList: [],
      getCredentialData: {
        url: common.credentialList,
        name:'',
      },

      //接口详情
      hostGroupName: '',
      getServersgroupDetail: {
        url: common.servergrouplDetail,
      },


      //查询服务器列表
      gitdatalist: [],
      gitdataTotal: 0,
      gitdata: {
        url: common.gitdata,
        name:'',
        page: '',
        limit: '',
      },
      ServerList: [],
      ServerTotal: 0,
      getServersData: {
        url: common.serverList,
        params: {
          hostname: '',
          public_ip: '',
          private_ip: '',
          os_version: '',
          disk: '',
          machine_type: '',
          cpu_num: '',
          memory: '',
          put_shelves_date: '',
          ssh_ip:'',
          ssh_port:'',
          hostgroupID:'',
          page: '',
          limit: '',
        }
      },
      //新增和更新复用部分字段
      creategitDrawer: false,
      gitname: "git",
      createserverData: {
        url: common.gitadd,
        name:'',
        git_token:'',
        git_url:'',
      },
      //创建server的表单校验规则
      createserverRules: {
        name: [{
          required: true,
          message: '请填写用户名',
          trigger: 'change'
        }],
        git_token: [{
          required: true,
          message: '请填写token',
          trigger: 'change'
        }],
        git_url: [{
          required: true,
          message: '请填写url地址',
          trigger: 'change'
        }],
      },


      //修改
      updatagitDrawer: false,
      updategitData: {
        url: common.gitupdate,
        gitID:'',
      },

      //同步
      syncdata: {
        url: common.syncdate,
        serverid:'',
        user:'',
        password:'',
        ssh_ip:'',
        ssh_post:'',
        credentialID:'',
      },
      //删除
      delServerData: {
        url: common.serverDelete,
        params: {
          id:'',
          Server_name: '',
        }
      },
      currentRow: '',  //将数据传递给子组件
      sshDialogVisible: false,
    }
  },
  methods: {
    //创建
    createserverFunc() {
      //赋值
      this.createserverData.name = this.gitname

      httpClient.post(this.createserverData.url, this.createserverData)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.gitlist()
            this.creategitDrawer = false
            this.appLoading = false
          })
    },
    //提交表单，验证数据
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.createserverFunc()
        } else {
          return false
        }
      })
    },

    //读取servergroup列表
    servergroup() {
      httpClient.get(this.getServersgroupData.url)
          .then(res => {
            this.ServergroupList = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //读取credential列表
    credential() {
      httpClient.get(this.getCredentialData.url)
          .then(res => {
            this.CredentialList = res.data
            this.createserverData.name = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //修改
    modify_data(e) {
      this.updatagitDrawer = true
      //赋值获取当前服务器ID
      this.updategitData.id= e.row.id
    },

    updatagitFunc() {
      //赋值
      this.createserverData.name = this.gitname
      httpClient.put(this.updategitData.url, this.createserverData)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.gitlist()
            this.updatagitDrawer = false
            this.appLoading = false
          })
    },

    sync(e){
      //赋值
      this.syncdata.serverid = e.row.id
      this.syncdata.ssh_ip = e.row.ssh_ip
      // this.syncdata.sship = "1.1.1.1"
      // this.syncdata.sshport = "222"
      this.syncdata.ssh_post = e.row.ssh_port
      this.syncdata.credentialID = e.row.Credentials[0].id
      this.syncdata.user = e.row.Credentials[0].user
      this.syncdata.password = e.row.Credentials[0].password

      httpClient.post(this.syncdata.url,  this.syncdata)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })

          })
          .finally(() => {
            this.getServers()
          })
    },

    getServers() {
      this.appLoading = true
      this.getServersData.params.page = this.currentPage
      this.getServersData.params.limit = this.pagesize
      httpClient.get(this.getServersData.url, {params: this.getServersData.params})
          .then(res => {
            this.ServerList = res.data
            this.ServerTotal = res.data.total
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      this.appLoading = false
    },

    gitlist() {
      this.gitdata.page = this.currentPage
      this.gitdata.limit = this.pagesize
      httpClient.get(this.gitdata.url, {params: this.gitdata})
          .then(res => {
            this.gitdatalist = res.data
            console.log(this.gitdatalist)
            this.gitdataTotal = res.data.total
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    delServer(e) {
      this.delServerData.params.id = e.row.id
      httpClient.delete(this.delServerData.url, {data: this.delServerData.params})
          .then(res => {
            this.getServers()
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //分页属性
    handleSizeChange(size) {
      this.pagesize = size;
      this.getServers()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getServers()
    },
    //选择判断
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {});
    },


    handleConfirm(obj, operateName, fn) {
      this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
      this.$confirm(this.confirmContent,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
          .then(() => {
            fn(obj)
          })
          .catch(() => {
            this.$message.info({
              message: '已取消操作'
            })
          })
    },
    SSH(index, row) {
      this.currentRow = row;
      this.sshDialogVisible = true;
    },
  },
  //注册子组件
  components: {
    SSH,
  },


  //beforeMount() {
  created() {
    //this.getServers()
    //this.servergroup()
    this.gitlist()
    this.credential()

  }
}
</script>


<style scoped>
.Server-head-card,.Server-body-card {
  border-radius: 10px;
  margin-bottom: 20px;
}
.Server-head-search {
  width:160px;
  margin-right:10px;
}
.Server-body-Servername {
  margin: 0px;
  color: #4795EE;
}
.Server-body-ip {
  margin: 0px;
  color: rgb(145, 145, 145);
}
.Server-body-Servername:hover {
  color: rgb(84, 138, 238);
  cursor: pointer;
  font-weight: bold;
}
</style>